<template>
  <div class="main">

    <!-- 路由视图 -->
    <router-view 
    :shop-product-list="shopProductList" 
     @del="del"
     @toggleAll="toggleAll" 
     @add="add" 
     @subBtn="subBtn" 
     @addBtn="addBtn" 
     @checked="checked"
     @add-local="addLocal"
     >
    </router-view>

    <!-- 缓存组件 提高性能效率 -->
    <!-- <keep-alive>
      <router-view 
        :shop-product-list="shopProductList" 
         @del="del"
         @toggleAll="toggleAll" 
         @add="add" 
         @subBtn="subBtn" 
         @addBtn="addBtn" 
         @checked="checked"
         @add-local="addLocal"
         v-if="$route.meta.keep"
         >
      </router-view>
    </keep-alive> -->

  </div>
</template>

<script>
  export default {
    data:function(){
      return {
        // 购物车数据
        shopProductList:[]
      }
    },

    methods:{
      // 添加购物车方法
      add(obj){
        let {id,size}  =  obj;
        // console.log(id);
        let index = this.shopProductList.findIndex(item => item.id == id);
        let indexSize = this.shopProductList.findIndex(item => item.size == size)
        if(index == -1){
          this.shopProductList.push(obj)

        }else{
          if(indexSize == -1){
            this.shopProductList.push(obj)
          }else{
            this.shopProductList[index].num += 1;
          }
        }
        // console.log(this.shopProductList);
      },

      // 减少商品数量
      subBtn(index){

        if(this.shopProductList[index].num > 1){
          this.shopProductList[index].num -= 1
        }else{
          this.shopProductList[index].num;
          this.$toast("不能再减了")
        }
      },

      // 增加商品数量
      addBtn(index){
        if(this.shopProductList[index].num < this.shopProductList[index].checkNum){
          this.shopProductList[index].num += 1

        }else{
          this.$toast("库存不足")
        }
       
      },
      // 全选方法
      toggleAll(value){
          this.shopProductList.forEach(item =>{
              item.checked = value;
          })
      },
      // 单选按钮方法
      checked(index){
        this.shopProductList[index].checked = !this.shopProductList[index].checked;
      },
      // 删除方法
      del(index){
        this.shopProductList.splice(index,1);
      },
      addLocal(){
        // 重新渲染购物车的商品，显示未被购买的数组
        this.shopProductList = this.shopProductList.filter(item => !item.checked);
        console.log(this.shopProductList);
      }
    }
  }
</script>

<style lang="scss" scoped>
// 公共css文件
@import "./assets/css/base.css"

</style>